package team.you.ticket.service.serviceImpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import team.you.ticket.dao.MessageMapper;
import team.you.ticket.dao.UserMapper;
import team.you.ticket.pojo.Message;
import team.you.ticket.pojo.Result;
import team.you.ticket.pojo.User;
import team.you.ticket.service.UserService;
import team.you.ticket.util.Md5Util;
import team.you.ticket.util.Sendsms;
import team.you.ticket.util.UpUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MessageMapper messageMapper;
    @Override
    public Result upImg(MultipartFile file, HttpServletRequest request) {
        Result result=new Result();
        try {
            UpUtils.upImgFile(file,request);
            String fileName= file.getOriginalFilename();
            result.setMsg(fileName);
            return result;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            result.setCode(500);
            result.setMsg("上传失败");
            return result;
        }
    }

    @Override
    public Result mobileCode(String phone, HttpServletRequest request) {
        Result result = new Result();
        Result sms = Sendsms.sms(phone);
        if(sms.getCode() == 2){
            Integer mobileCode = sms.getCount();
            request.getSession().setAttribute("mobileCode",mobileCode);
            request.getSession().setMaxInactiveInterval(300);
            result.setMsg(sms.getMsg());
            return result;
        }else {
            result.setCode(sms.getCode());
            result.setMsg(sms.getMsg());
            return result;
        }
    }

    @Override
    public Result register(User user) {
        Result result = new Result();
        try {
            User user1=userMapper.selectByUsername(user.getUsername());
            if(user1==null)
            {
                String id = UUID.randomUUID().toString();
                String password = Md5Util.encryption(user.getUsername(),user.getPassword());//密码加密
                user.setPassword(password);
                String headImg = "/img/" + user.getHead();
                User newUser = new User(id,user.getUsername(),user.getPassword(),user.getPhone(),user.getPapers(),"0","",user.getHead(),headImg);
                userMapper.insert(newUser);
                result.setMsg("注册成功");
                return result;
            }
            else
            {
                result.setCode(500);
                result.setMsg("用户名重复");
                return result;
            }
        }catch (Exception e){
            result.setCode(500);
            result.setMsg("系统繁忙，请稍后重试！");
            return result;
        }
    }

    @Override
    public Result login(String remember, String username, String password, String code, HttpServletRequest request) {
        Result result = new Result();
        String newCode = (String)request.getSession().getAttribute("code");//获取验证码
        if(newCode.equalsIgnoreCase(code)){
            User user = userMapper.selectByUsername(username);
            String pwd = Md5Util.encryption(username,password);
            if(user != null && pwd.equals(user.getPassword())){
                request.getSession().setAttribute("user",user);
                if(remember.equals("0")){
                    request.getSession().setMaxInactiveInterval(60*60);
                }
                else request.getSession().setMaxInactiveInterval(60);
                return result;
            }else{
                result.setCode(500);
                result.setMsg("用户名或密码错误！");
                return result;
            }
        }else{
            result.setCode(500);
            result.setMsg("验证码错误！");
            return result;
        }
    }

    @Override
    public Result getAllUsers(Integer page,Integer limit) {
        Result result=new Result();
        if(page<=0)
        {
            page=1;
            page=(page-1)*limit;
        }
        else page=(page-1)*limit;
        List<User> users = userMapper.selectAll(page,limit);
        Integer count=userMapper.getCount();
        result.setData(users);
        result.setCount(count);
        return result;
    }

    @Override
    public Result del(String id) {
        Result result=new Result();
        User user=userMapper.selectByPrimaryKey(id);
        if (user!=null)
        {
            userMapper.deleteByPrimaryKey(id);
            result.setMsg("删除成功");
        }
        else
        {
            result.setCode(500);
            result.setMsg("删除失败");
        }
        return result;
    }

    @Override
    @Transactional //添加事务
    //事务 做事时，要么全部成功，要么全部失败 如果出现异常，必须全部回滚
    public Result delete(String[] ids) {
        Result result=new Result();
        try {
            for (int i = 0; i < ids.length; i++)
            {
                userMapper.deleteByPrimaryKey(ids[i]);
            }
            return result;
        }catch (Exception e)
        {
            e.printStackTrace();
            result.setCode(500);
            result.setMsg("系统繁忙");
            return result;
        }
    }

    @Override
    public Result update(String id, String value, String field) {
        Result result=new Result();
        if (field.equals("username"))
        {
            try {
                User user=userMapper.selectByPrimaryKey(id); //防止重复用户名
                if (user==null)
                {
                    return getResult(id, field, result, value);
                }
                else
                {
                    result.setCode(500);
                    result.setMsg("更新失败!用户名以被使用");
                    return result;
                }
            }
            catch (Exception e)
            {
                e.printStackTrace();
                result.setCode(500);
                result.setMsg("系统繁忙");
                return result;
            }
        }
        else
        {
            try {
                return getResult(id, field, result, value);
            }
            catch (Exception e)
            {
                e.printStackTrace();
                result.setCode(500);
                result.setMsg("系统繁忙");
                return result;
            }
        }
    }
    //重复部分提取
    private Result getResult(String id, String field, Result result, String value) {
        Integer i=userMapper.UpdateByKey(id,value,field);
        if(i==1)
        {
            result.setMsg("更新成功");
            return result;
        }
        else
        {
            result.setCode(500);
            result.setMsg("更新失败");
            return result;
        }
    }

    @Override
    public Result userNameChange(String value) {
        Result result=new Result();
        User user=userMapper.selectByUsername(value);
        if (user==null)
        {
            return result;
        }
        else
        {
            result.setCode(500);
            return result;
        }
    }

    @Override
    public Result selectByLike(String value, String type, Integer page, Integer limit) {
        Result result=new Result();
        if(page<=0)
        {
            page=1;
            page=(page-1)*limit;
        }
        else page=(page-1)*limit;
        Integer type0=Integer.parseInt(type);
        List<User> users = userMapper.selectByLike(value,type0,page,limit);
        List<User> count=userMapper.selectByLike(value,type0,null,null);
        result.setData(users);
        result.setCount(count.size());
        return result;
    }

    @Override
    public Result pwd(String username, String mobileCode, HttpServletRequest request) {
        Result result=new Result();
        User user=userMapper.selectByUsername(username);
        if (user!=null)
        {
            Integer code1 = (Integer) request.getSession().getAttribute("mobileCode");
            if(code1 != null){
                String code = code1.toString();
                if(mobileCode.equals(code)){
                    try {
                        String pwd=Md5Util.encryption(user.getUsername(),"123456");
                        user.setPassword(pwd);
                        Integer i=userMapper.updateByPrimaryKey(user);
                        if (i==1)
                        {
                            result.setMsg("您的密码已经重置为：123456");
                            return result;
                        }
                        else
                        {
                            result.setCode(500);
                            result.setMsg("密码重置失败");
                            return result;
                        }
                    }catch (Exception e)
                    {
                        e.printStackTrace();
                        result.setCode(500);
                        result.setMsg("系统繁忙");
                        return result;
                    }
                }else {
                    result.setCode(500);
                    result.setMsg("验证码过期或有误！");
                    return result;
                }
            }else {
                result.setCode(500);
                result.setMsg("请先获取验证码！");
                return result;
            }
        }
        else
        {
            result.setCode(500);
            result.setMsg("用户名不存在");
            return result;
        }
    }

    @Override
    public Result getCode(String username, HttpServletRequest request) {
        User user=userMapper.selectByUsername(username);
        if (user!=null)
        {
            return mobileCode(user.getPhone(),request);
        }
        else
        {
            Result result=new Result();
            result.setCode(500);
            result.setMsg("用户名不存在");
            return result;
        }
    }

    @Override
    public Result updateInfoCode(String id, HttpServletRequest request) {
        User user=userMapper.selectByPrimaryKey(id);
        if(user!=null)
        {
            return mobileCode(user.getPhone(),request);
        }
        else
        {
            Result result=new Result();
            result.setCode(500);
            result.setMsg("用户不存在");
            return result;
        }
    }
    @Override
    public Result updateInfo(String id,String mobileCode, String username, String password, String phone, String papers, String remarks, HttpServletRequest request) {
        Result result = new Result();
        User user = userMapper.selectByPrimaryKey(id);
        if (user != null) {
            Integer code1 = (Integer) request.getSession().getAttribute("mobileCode");
            if (code1 != null) {
                String code = code1.toString();
                if (mobileCode.equals(code)) {
                    try {
                        user.setUsername(username);
                        //password为null，则不修改密码
                        String pwd=(password==null || password=="")? user.getPassword():Md5Util.encryption(username,password);
                        user.setPassword(pwd);
                        user.setPhone(phone);
                        user.setPapers(papers);
                        user.setRemarks(remarks);
                        Integer i = userMapper.updateByPrimaryKey(user);
                        if (i == 1) {
                            result.setMsg("您的信息已经修改");
                            return result;
                        } else {
                            result.setCode(500);
                            result.setMsg("信息修改失败");
                            return result;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        result.setCode(500);
                        result.setMsg("系统繁忙");
                        return result;
                    }
                } else {
                    result.setCode(500);
                    result.setMsg("验证码过期或有误！");
                    return result;
                }
            } else {
                result.setCode(500);
                result.setMsg("请先获取验证码！");
                return result;
            }
        } else {
            result.setCode(500);
            result.setMsg("用户不存在");
            return result;
        }
    }

    @Override
    public Result InfoLoad(String userid) {
        Result result=new Result();
        try {
            User user=userMapper.selectByPrimaryKey(userid);
            if (user!=null)
            {
                List<User> users = new ArrayList<User>();
                users.add(user);
                result.setData(users);
                return result;
            }
            else
            {
                result.setCode(500);
                result.setMsg("用户信息预加载失败");
                return result;
            }
        }catch (Exception e)
        {
            e.printStackTrace();
            result.setCode(500);
            result.setMsg("系统繁忙");
            return result;
        }
    }

    @Override
    public Result getMsg() {
        Result result=new Result();
        List<Message> messages=messageMapper.selectById();
        if (messages!=null)
        {
            result.setMsg("加载成功");
            result.setData(messages);
            return result;
        }
        else
        {
            result.setCode(500);
            result.setMsg("加载失败");
            return result;
        }
    }
}
